<?php
namespace app\http;

use app\models\MembershipCard;
use think\worker\Server;
use app\servers\MembershipCardServer;
use Workerman\Lib\Timer;

class Worker extends Server
{
    protected $socket = 'tcp://0.0.0.0:2347';
    protected static $conns = [];
    protected static $redisWorker;
    private static $time_id = -1;

    private static $config = [
        'host' => '192.168.2.3',  //服务器连接地址。默认='127.0.0.1'
        'port' => '6379',  //端口号。默认='6379'
        //'expire' => '',  // 默认全局过期时间，单位秒。不填默认3600
        'password' => '',  // 连接密码，如果有设置密码的话
        'db' => 1,   //缓存库选择。默认0
        'timeout' => 10  // 连接超时时间（秒）。默认10
    ];

    public function onWorkerStart($worker){
        self::$redisWorker = new Redis(self::$config);

        self::$time_id = Timer::add(3, function(){
            $_redis = self::$redisWorker;
            if(!$_redis || !$_redis::ping()){
                $_redis = self::$redisWorker = new Redis(self::$config);
            }

            $_res = $_redis::lpop('HENG_TONG_DOWN_FACE_SERVER_KEYS');
            if($_res) {
                $_comd = json_decode($_res, true);

                if (array_key_exists('cmd', $_comd)) {
                    switch ($_comd['cmd']) {
                        case 'AH'://下发用户信息
                        {
                            if (array_key_exists('data', $_comd)) {
                                if (array_key_exists('user_id', $_comd['data'])) {
                                    //$_comd['data']['user_id']

                                    //卡号
                                    $card = dechex($_comd['data']['card_code']);
                                    if (strlen($card) < 8) {
                                        $card2 = str_pad($card, 8, 0, STR_PAD_LEFT);
                                    }else{
                                        $card2 = $card;
                                    }
                                    //图片
                                    $path = 'http://192.168.2.3/attachment/' . $_comd['data']['userpic'];

                                    $imgs = file_get_contents($path);
                                    $imgsez = $_comd['data']['file_size'];
                                    $img_len_1 = bin2hex($imgs);
                                    //计算长度
                                    $_len = $imgsez + 3 + 4 + 1 + 1 + 2;
                                    $img_len = dechex($_len);

                                    $_member = new MembershipCardServer();
                                    $str_2 = $_member->reStrings($img_len);

                                    if (strlen($str_2) < 6) {
                                        $imgLen = str_pad($str_2, 6, 0, STR_PAD_RIGHT);
                                    }
                                    //CRC
                                    $result2 = '444D' . $imgLen . $card2 . $img_len_1;
                                    $value = '';
                                    for ($i = 0; $i < strlen($result2); $i += 2) {
                                        $char = substr($result2, $i, 2);
                                        if (!$value) {
                                            $value = hexdec($char);
                                        } else {
                                            $value ^= hexdec($char);
                                        }
                                    }
                                    //发送
                                    $result5 = $result2 . dechex($value) . '21';

                                    foreach (self::$conns as $conn) {
                                        //$conn->send(pack('H*',$result5));
                                        $vres = $conn->send(pack('H*', $result5));

                                        if ( $vres == true) {
                                            //成功逻辑
                                            $data = ['code' => 0, 'msg' => '下发成功'];//success

                                        } else {
                                            $data = ['code' => 1, 'msg' => '下发失败'];
                                        }
                                    }

                                }
                            }
                            break;
                        }
                        default :
                        {
                            //默认处理
                            break;
                        }
                    }
                }
            }
        });
    }

    public function onConnect($connection)

    {

        $connection->send("tcp连接\n");

    }

    public function onMessage($connection ,$data)
    {
        $menm = new MembershipCardServer;

        //dechex()十进制转十六进制
        if($data){
            $str = bin2hex($data);//二进制转16进制
            $cmd = substr($str,0,4);
            $len = substr($str,strlen($cmd),2);

            switch ($cmd){
                case '4842':  //心跳包
                {
                    $card_no = substr($str,(strlen($cmd)+strlen($len)),8);

                    if(!array_key_exists($card_no, self::$conns)){
                        self::$conns[$card_no] = $connection;
                    }

                    $_year = str_pad(dechex(date('y')), 2, '0', STR_PAD_LEFT);
                    $_month = str_pad(dechex(date('m')), 2, '0', STR_PAD_LEFT);
                    $_day = str_pad(dechex(date('d')), 2, '0', STR_PAD_LEFT);
                    $_hour = str_pad(dechex(date('H')), 2, '0', STR_PAD_LEFT);
                    $_minute = str_pad(dechex(date('i')), 2, '0', STR_PAD_LEFT);
                    $_second = str_pad(dechex(date('s')), 2, '0', STR_PAD_LEFT);

                    $_pong = '48420F' . $card_no . $_year . $_month . $_day . $_hour . $_minute .$_second;
                    $_crc = $menm->Hex_CRC($_pong);
                    $_pong .= $_crc . '21';
                    var_dump($_pong);
                    $connection->send(pack('H*', $_pong));
                    break;
                }
                case '5443':  //刷脸消费
                {
                    $len = substr($str,strlen($cmd),2);
                    $results['cmd'] = $cmd;
                    $results['len'] = $len;
                    $results['card'] = substr($str,(strlen($cmd)+strlen($len)),8);
                    $results['amount'] = substr($str,(strlen($cmd)+strlen($len)+strlen($results['card'])),8);
                    $results['device'] = substr($str,(strlen($cmd)+strlen($len)+strlen($results['card'])+strlen($results['amount'])),8);
                    $results['time'] = substr($str,(strlen($cmd)+strlen($len)+strlen($results['card'])+strlen($results['amount'])+strlen($results['device'])),12);
                    $results['no'] = substr($str,(strlen($cmd)+strlen($len)+strlen($results['card'])+strlen($results['amount'])+strlen($results['device'])+strlen($results['time'])),4);
                    $results['type'] = substr($str,(strlen($cmd)+strlen($len)+strlen($results['card'])+strlen($results['amount'])+strlen($results['device'])+strlen($results['time'])+strlen($results['no'])),2);
                    $results['model'] = substr($str,(strlen($cmd)+strlen($len)+strlen($results['card'])+strlen($results['amount'])+strlen($results['device'])+strlen($results['time'])+strlen($results['no'])+strlen($results['type'])),2);
                    $results['menu'] = substr($str,(strlen($cmd)+strlen($len)+strlen($results['card'])+strlen($results['amount'])+strlen($results['device'])+strlen($results['time'])+strlen($results['no'])+strlen($results['type'])+strlen($results['model'])),2);
                    $crc = substr($str,(strlen($cmd)+strlen($len)+strlen($results['card'])+strlen($results['amount'])+strlen($results['device'])+strlen($results['time'])+strlen($results['no'])+strlen($results['type'])+strlen($results['model'])+strlen($results['menu'])),2);
                    $end = substr($str,(strlen($cmd)+strlen($len)+strlen($results['card'])+strlen($results['amount'])+strlen($results['device'])+strlen($results['time'])+strlen($results['type'])+strlen($results['model'])+strlen($results['menu'])+strlen($crc)+strlen($results['no'])),2);
                    //卡号
                    $card = $menm->conversion($results['card']);//卡号
                    //金额
                    $amount1 =  substr($results['amount'],0,2);
                    $amount2 =  substr($results['amount'],strlen($amount1),6);
                    $amount  = hexdec($amount2) ;//消费金额
                    //设备
                    $device1 = substr($results['device'],0,4);
                    $device2 = substr($results['device'],strlen($device1),2);
                    $device = substr($results['device'],(strlen($device1)+strlen($device2)),2);//设备号

                    $time = $menm->conversion($results['time']);//消费序列号
                    $no = $menm->conversion($results['no']);//消费序列号

                    $type = hexdec($results['type']);//消费类型
                    $model = hexdec($results['model']);//卡号模式
                    $menu = hexdec($results['menu']);

                    //查询会员卡
                    $cardModel = new MembershipCard();
                    $menmcard =  $cardModel->where('card_code',$card)->find();

                    $name = $menmcard['username'];
                    $nameStr = iconv("UTF-8", "GB2312//IGNORE",$name);
                    $nameData = $menm->strToHex($nameStr);
                    //如果名字不足8个字节16位自动用20补齐
                    if(strlen($nameData) < 16){
                        $nameData =  str_pad($nameData,16,20,STR_PAD_RIGHT);
                    }

                    $balance  = dechex(intval($menmcard['totalprice']*100));
                    if(strlen($balance)<8){
                        $balance =  str_pad($balance,8,0,STR_PAD_LEFT);
                    }

                    //卡号（4个字节）姓名（4个汉字，8个字节）现金余额（4个字节）补贴余额（4个字节）现金消费金额（4个字节）补贴消费金额（4个字节）卡类（1个字
                    $results2 = '545322'.$results['card'].$nameData.$balance.'00000000'.$results['amount'].'0000000001';
                    $_value = '';
                    for($i=0;$i<strlen($results2);$i+=2){
                        $char = substr($results2,$i,2);
                        if(!$_value){
                            $_value = hexdec($char);
                        }else{
                            $_value ^= hexdec($char);
                        }
                    }
                    //消费成功返回
                    $result = '545322'.$results['card'].$nameData.$balance.'00000000'.$results['amount'].'0000000001'.dechex($_value).'21';
                    $retu = $connection->send(pack('H*',$result)); //16 jinzzfczhuan16jinz

                    if($retu == true ){
                        $num = $menmcard['totalprice'] - ($amount/100);
                        $cardModel->where('card_code',$card)->update(['totalprice'=>$num]);

                    }
                }
            }

        }

    }

    // 当客户端的连接上发生错误时触发
    public function onErroe($connection,$code,$msg)
    {
        echo "error $code $msg\n";
    }




}